/*
 *  JVending - JSP Tag Library
 *  Copyright (C) 2004  Shane Isbell
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package org.jvending.provisioning.taglib;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.logging.*;

import javax.provisioning.BundleDescriptor;
import javax.provisioning.BundleRepository;
import javax.provisioning.Capabilities;
import javax.provisioning.DeliveryContext;
import javax.provisioning.ProvisioningContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.BodyContent;

import org.jvending.provisioning.match.BundleTypeMatch;
import org.jvending.provisioning.match.CategoryMatch;
import org.jvending.provisioning.match.KeywordSearch;

import org.jvending.provisioning.stocking.DataSink;

/**
 * @author Shane Isbell
 * @since 1.3.9a
 */

public class BundleDescriptorTag extends BodyTagSupport {

    private static Logger logger = Logger.getLogger("BundleDescriptorTag");

    private Iterator descriptors;

    private StringBuffer buffer = new StringBuffer();

    private String allVersions;

    private String allVariants;

    private String bundleId;

    private String dataSource;

    private String keywords;

    private String category;

    private String bundleType;

    private String deviceId;

    public String getAllVersions() {
        return allVersions;
    }

    public void setAllVersions(String allVersions) {
        this.allVersions = allVersions;
    }

    public String getAllVariants() {
        return allVariants;
    }

    public void setAllVariants(String allVariants) {
        this.allVariants = allVariants;
    }

    public String getBundleId() {
        return bundleId;
    }

    public void setBundleId(String bundleId) {
        this.bundleId = bundleId;
    }

    public void setDataSource(String dataSource) {
        this.dataSource = dataSource;
    }

    public String getDataSource() {
        return dataSource;
    }

    public String getKeywords() {
        return keywords;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getCategory() {
        return category;
    }

    public void setBundleType(String bundleType) {
        this.bundleType = bundleType;
    }

    public String getBundleType() {
        return bundleType;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public int doStartTag() throws JspTagException {
        ProvisioningContext provisioningContext = (ProvisioningContext)
             pageContext.getAttribute("javax.provisioning.ProvisioningContext", 
                                       pageContext.APPLICATION_SCOPE);
        if(provisioningContext == null) return SKIP_BODY;

        BundleRepository bundleRepository = provisioningContext.getBundleRepository();
      //  if(dataSource != null) ((DataSink) bundleRepository).setDataSourceName(dataSource);

        boolean aVariants = (allVariants != null && allVariants.equals("true")) ? true: false;
        boolean aVersions = (allVersions != null && allVersions.equals("true")) ? true: false;
        if(keywords != null && keywords.equals("")) keywords = null;
        if(category != null && category.equals("")) category = null;
        if(deviceId != null && deviceId.equals("")) deviceId = null;

        try {
            if(bundleId != null) {
                BundleDescriptor descriptor = bundleRepository.getBundleByID(bundleId);
                if(descriptor == null) {
                    logger.info("Could not find bundle: ID = " + bundleId);
                    return SKIP_BODY;
                }
                List list = new ArrayList();
                list.add(descriptor);
                descriptors = list.iterator();
            } else {
                List policies = new ArrayList();
                if(keywords != null) policies.add(new KeywordSearch(keywords));

                if(category != null && !category.equalsIgnoreCase("all")) {
                    List categories = new ArrayList();
                    categories.add(category);
                    policies.add(new CategoryMatch(categories));
                }

                if(bundleType != null && !bundleType.equalsIgnoreCase("all")) {
                    List bundleTypes = new ArrayList();
                    bundleTypes.add(bundleType);
                    policies.add(new BundleTypeMatch(bundleTypes));
                }

                Capabilities capabilities = null;
                if(deviceId != null && deviceId.equalsIgnoreCase("AutoDetect")) {
                    logger.finest("Auto detecting device.");
                    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
                    DeliveryContext deliveryContext = 
                        provisioningContext.getDeliveryContext(request);
                    capabilities = deliveryContext.getDeviceCapabilities();
                } else if(deviceId != null) {
                    capabilities = provisioningContext.getDeviceTypeCapabilities(deviceId);
                }

                Collection bundleDescriptors = 
                    bundleRepository.getBundlesFor(capabilities, policies, aVersions, aVariants);
                if(bundleDescriptors == null || bundleDescriptors.size() == 0) return SKIP_BODY;
                descriptors = bundleDescriptors.iterator();
            }
        } catch(IOException e) {
            e.printStackTrace();
        }

        pageContext.setAttribute("descriptor", (BundleDescriptor) descriptors.next());
        return EVAL_BODY_BUFFERED;
    }

    public int doAfterBody() throws JspTagException {     
        BodyContent bodyContent = getBodyContent();
        if(bodyContent != null) {
            buffer.append(bodyContent.getString());
            try {
                bodyContent.clear();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }

       if(descriptors.hasNext()) {
            pageContext.setAttribute("descriptor", (BundleDescriptor) descriptors.next());
            return EVAL_BODY_BUFFERED;
        } else
            return SKIP_BODY;
    }

    public int doEndTag() throws JspTagException {
        BodyContent bodyContent = getBodyContent();
        try {
            if(bodyContent != null) bodyContent.getEnclosingWriter().write(buffer.toString());
        } catch(IOException e) {
            e.printStackTrace();
            throw new JspTagException("Could not End Tag");
        } finally {
            buffer = new StringBuffer();
        }
        return EVAL_PAGE;
    }

}